package com.piece.core.authentication.handler;

import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.web.properties.SecurityProperties;
import com.piece.core.web.util.ServletUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义匿名用户无权限异常
 */
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {

    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private final SecurityProperties securityProperties;

    public AuthenticationEntryPointHandler (SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        if (ServletUtil.isAjaxRequest(request)) {
            ServletUtil.renderString(response, JsonUtil.toJson(AjaxResponse.error(401, e.getMessage())));
        } else {
            redirectStrategy.sendRedirect(request, response, securityProperties.getProcess().getLoginUrl());
        }
    }
}
